import os

from minio import Minio, commonconfig, datatypes
from datetime import timedelta

# 从环境变量获取配置
MINIO_SECRET_KEY = os.getenv(
    "MINIO_SECRET_KEY", "I7dC6TKHVT23TqNJBozvZBuuDyqMSryn8DT2w3bK"
)
MINIO_ACCESS_KEY = os.getenv("MINIO_ACCESS_KEY", "ytXBTtZvRQMSUHjwtp9z")
MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
MINIO_BUCKET_NAME = os.getenv("MINIO_BUCKET_NAME", "zq1")

# 初始化MinIO客户端
minio_client = Minio(
    endpoint="127.0.0.1:9000",  # MinIO服务地址
    access_key=MINIO_ACCESS_KEY,  # 访问密钥
    secret_key=MINIO_SECRET_KEY,  # 秘密密钥
    secure=False,  # 是否使用HTTPS
)


def minio_get_bucket_list() -> list:
    # 获取所有存储桶列表
    try:
        buckets = minio_client.list_buckets()
        return buckets
    except Exception as e:
        print("获取存储桶列表失败:", e)
        return []


def minio_create_bucket(bucket_name: str) -> bool:
    # 创建存储桶
    try:
        minio_client.make_bucket(bucket_name)
        return True
    except Exception as e:
        print("创建存储桶失败:", e)
        return False


def minio_check_bucket_exists(bucket_name: str) -> bool:
    # 检查存储桶是否存在
    try:
        if minio_client.bucket_exists(bucket_name):
            print(f"存储桶 {bucket_name} 已存在.")
            return True
        else:
            print(f"存储桶 {bucket_name} 不存在.")
            return False
    except Exception as e:
        print("检查存储桶失败:", e)
        return False


def minio_get_presigned_download_url(key: str, expires_in: int = 60) -> str | None:
    # 生成预签名下载链接
    try:
        presigned_url = minio_client.get_presigned_url(
            method="GET",
            bucket_name=MINIO_BUCKET_NAME,  # 存储桶名称
            object_name=key,  # 对象名称
            expires=timedelta(seconds=expires_in),
        )
        # print("预签名下载链接:", presigned_url)
        return presigned_url
    except Exception as e:
        print("生成预签名URL失败:", e)
        return None


# curl -X PUT -H "Content-Type: text/plain" --upload-file vite.config.ts "http://127.0.0.1:9000/zq1/1111.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ytXBTtZvRQMSUHjwtp9z%2F20250406%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250406T102526Z&X-Amz-Expires=60&X-Amz-SignedHeaders=host&X-Amz-Signature=d8fb039574cf6b9eeec6aad5fa750acbdab19f5e0b607185f88bd372a6be4bfd"
def minio_get_presigned_upload_url(key: str, expires_in: int = 60) -> str | None:
    # 生成预签名上传链接
    try:
        presigned_url = minio_client.presigned_put_object(
            bucket_name=MINIO_BUCKET_NAME,  # 存储桶名称
            object_name=key,  # 对象名称
            expires=timedelta(seconds=expires_in),
        )
        # print("预签名上传链接:", presigned_url)
        return presigned_url
    except Exception as e:
        print("生成预签名URL失败:", e)
        return None


def minio_get_object_tags(key: str) -> dict | None:
    try:
        # 获取对象的标签
        tags: commonconfig.Tags = minio_client.get_object_tags(
            bucket_name=MINIO_BUCKET_NAME,
            object_name=key,  # 对象名称
            version_id=None,  # 版本ID（如果使用版本控制）
        )
        return dict(tags) if tags else None
    except Exception as e:
        print(f"获取对象标签失败: {e}")
        return None


def minio_get_object_metadata(key: str) -> dict | None:
    try:
        # 获取对象的元信息
        object_metadata: datatypes.Object = minio_client.stat_object(
            bucket_name=MINIO_BUCKET_NAME,
            object_name=key,  # 对象名称
            version_id=None,  # 版本ID（如果使用版本控制）
        )
        return {
            "content_type": object_metadata.content_type,
            "size": object_metadata.size,
            "last_modified": object_metadata.last_modified,
            "etag": object_metadata.etag,
            "user_metadata": object_metadata.metadata,
        }
    except Exception as e:
        print(f"获取对象元信息失败: {e}")
        return None


if __name__ == "__main__":
    # print(
    #     minio_get_presigned_download_url(
    #         "caravan palace (slowed + reverb) - lone digger.mp3"
    #     )
    # )
    # print(minio_get_presigned_upload_url("1111.txt", "text/plain"))
    # print(
    #     minio_get_object_metadata("caravan palace (slowed + reverb) - lone digger.mp3")
    # )
    print(minio_get_object_metadata("1111.txt"))
